package com.slm.krstartimes.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.slm.krstartimes.R;
import com.slm.krstartimes.utils.L;
import com.slm.krstartimes.utils.SwipeRefreshLoadingLayout;
import com.slm.krstartimes.activity.MainActivity;
import com.slm.krstartimes.activity.NewsDetailActivity;
import com.slm.krstartimes.adapter.AndroidNewsAdapter;
import com.slm.krstartimes.db.sqlite.SQLiteDataBaseManager;
import com.slm.krstartimes.utils.News;
import com.slm.krstartimes.utils.NewsListSAX;
import com.slm.krstartimes.utils.StreamRequest;

import org.xml.sax.SAXException;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

/**
 * Created by dllo on 15/7/30.
 */
public class PhoneNewsFragment extends android.support.v4.app.Fragment {
    private Handler handler;
    private AndroidNewsAdapter newsAdapter;
    private ListView phoneListview;
    private SwipeRefreshLoadingLayout srff;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.phone_news_fragment, null);

        initView(view);

        getList();

        refresh();

        return view;

    }

    /**
     * 刷新
     */
    private void refresh() {
        srff.setOnRefreshListener(new SwipeRefreshLoadingLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getList();

            }
        });
        srff.setOnLoadListener(new SwipeRefreshLoadingLayout.OnLoadListener() {
            @Override
            public void onLoad() {

                Toast.makeText(getActivity(), "已是最后一条", Toast.LENGTH_SHORT).show();
                srff.setLoading(false);
            }
        });
    }

    /**
     * 初始化
     * @param view
     */
    private void initView(View view) {
        phoneListview = (ListView) view.findViewById(R.id.phoneListview);
        srff = (SwipeRefreshLoadingLayout) view.findViewById(R.id.srff_phone);
    }

    /**
     * 获取数据
     */
    private void getList() {
        StreamRequest request = new StreamRequest("http://api.ithome.com/xml/newslist/rank.xml",
                new Response.Listener<InputStream>() {
                    @Override
                    public void onResponse(InputStream inputStream) {
                        L.i("rank拉取成功" + inputStream);
                        handler = new Handler(new Handler.Callback() {
                            @Override
                            public boolean handleMessage(Message message) {
                                if (message.what == 10) {
                                    final List<News> list = (List<News>) message.obj;
                                    newsAdapter = new AndroidNewsAdapter(getActivity(), list);
                                    phoneListview.setAdapter(newsAdapter);
                                    srff.setRefreshing(false);
                                    Toast.makeText(getActivity(), "刷新成功", Toast.LENGTH_SHORT).show();
                                    MainActivity.sqLiteDataBaseTools.delete(SQLiteDataBaseManager.RANK);
                                    for (News news : list) {
                                        MainActivity.sqLiteDataBaseTools.insert(news.getNewsid(),
                                                news.getTitle(), news.getImage(), news.getHitcount(), news.getCommentcount(),
                                                SQLiteDataBaseManager.RANK);
                                    }
                                    phoneListview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                        @Override
                                        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                                            Intent newsDetail = new Intent(getActivity(), NewsDetailActivity.class);
                                            newsDetail.putExtra("newsId", list.get(i).getNewsid());
                                            newsDetail.putExtra("title", list.get(i).getTitle());
                                            newsDetail.putExtra("postdate", list.get(i).getPostdate());
                                            newsDetail.putExtra("hitCount", list.get(i).getHitcount());
                                            newsDetail.putExtra("image",list.get(i).getImage());
                                            startActivity(newsDetail);
                                        }
                                    });
                                }
                                return false;
                            }
                        });

                        Log.i("网络拉取成功", " phone");
                        SAXParserFactory spx = SAXParserFactory.newInstance();
                        try {
                            SAXParser sp = spx.newSAXParser();
                            sp.parse(inputStream, new NewsListSAX(handler));

                        } catch (ParserConfigurationException e) {
                            e.printStackTrace();
                        } catch (SAXException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(getActivity(), "刷新失败", Toast.LENGTH_SHORT).show();
                srff.setRefreshing(false);
                L.i("rank拉取失败" + volleyError);
                List<News> list = MainActivity.sqLiteDataBaseTools.query(SQLiteDataBaseManager.RANK);
                newsAdapter = new AndroidNewsAdapter(getActivity(), list);
                phoneListview.setAdapter(newsAdapter);
            }
        });
        MainActivity.requestQueue.add(request);
    }
}
